package com.qiyou.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.qiyou.dao.IActivityDao;
import com.qiyou.dao.factory.DaoFactory;
import com.qiyou.entity.Activity;
import com.qiyou.entity.User;

/**
 * 用户发起活动逻辑
 */
@WebServlet(name = "InitiateActivity", urlPatterns = { "/InitiateActivity" })
public class InitiateActivityServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        User user =  (User) request.getSession().getAttribute("user");
        
        String userID = user.getID();
        String acPlace = request.getParameter("acPlace");
        String acName = request.getParameter("acName");
        String acContent = request.getParameter("acContent");
        String acStartDate = request.getParameter("acStartDate");
        String acPathPic = request.getParameter("acPathPic");
        String max = request.getParameter("max");

        Activity activity = new Activity();
        activity.setUserID(userID);
        activity.setAcPlace(acPlace);
        activity.setAcName(acName);
        activity.setAcContent(acContent);
        activity.setAcPathPic(acPathPic);

        long maxNum = 5;
        try {
            maxNum = Long.parseLong(max);
        } catch (NumberFormatException e) {
            maxNum = 5;
        }
        activity.setMax(maxNum);

        Date date = new Date();
        try {
            date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                    .parse(acStartDate);
        } catch (ParseException e) {
            date = new Date();
        }
        activity.setAcStartDate(date);

        IActivityDao dao = DaoFactory.getActivityDao();
        boolean result = false;
        try {
            result = dao.doCreate(activity);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        if (result) {
            request.setAttribute("userID", userID);
            request.getRequestDispatcher("ActivityList").forward(request,
                    response);
        } else {
            response.getWriter()
                    .print("<script type='text/javascript'>alert('创建活动失败，请稍候再试!');history.go(-1);</script>");

        }

    }
}
